package com.ruoyi.email.service.impl;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.RedisUtil;
import com.ruoyi.common.utils.VerCodeGenerateUtil;
import com.ruoyi.dto.CheckCodeResultDto;
import com.ruoyi.email.domain.Email;
import com.ruoyi.email.service.IEmailService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;
/**
 * @program: RuoYi-Vue-master
 * @description:
 * @author: xgw
 * @create: 2025-01-10 09:33
 **/


@Service
public class EmailServiceImpl implements IEmailService {


    @Autowired
    private RedisUtil redisUtil;

    @Value("${spring.mail.username}")
    private String sendMailer;

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    /**
     * 检测邮件信息
     * @param receiveEmail 接收者
     * @param subject  主题
     * @param emailMsg 内容
     */
    public void checkMail(String receiveEmail, String subject, String emailMsg){
        //  StringUtils 需要引入  commons-lang3 依赖
        //  可以用 receiveEmail == null || receiveEmail.isEmpty() 来代替
        if(StringUtils.isEmpty(receiveEmail)) {
            throw new RuntimeException("邮件收件人不能为空");
        }
        if(StringUtils.isEmpty(subject)) {
            throw new RuntimeException("邮件主题不能为空");
        }
        if(StringUtils.isEmpty(emailMsg)) {
            throw new RuntimeException("邮件内容不能为空");
        }
    }

    /**
     * 发送纯文本邮件
     * @param receiveEmail 接收者
     * @param subject  主题
     * @param emailMsg 内容
     */
    public Boolean sendTextMail(String receiveEmail, String subject, String emailMsg) {
        // 参数检查
        checkMail(receiveEmail, subject, emailMsg);
        try {
            // true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            // 邮件发件人
            mimeMessageHelper.setFrom(sendMailer);
            // 邮件收件人
            mimeMessageHelper.setTo(receiveEmail.split(","));
            // 邮件主题
            mimeMessageHelper.setSubject(subject);
            // 邮件内容
            mimeMessageHelper.setText(emailMsg);
            // 邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
            // 发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            System.out.println("发送邮件成功: " + sendMailer + "-->" + receiveEmail);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送邮件失败: " + e.getMessage());
            return false;
        }
    }

    @Override
    public AjaxResult sendEmail(Email email) {
        // 获取验证码
        String verCode = VerCodeGenerateUtil.generateVerCode();
        // 将当前验证码存储进redis缓存
        // key:邮箱 valve：verCode  5分钟的超时时间
        //对于多次请求只保存最新的验证码
        String key = email.getTos();
        redisUtil.set(key,verCode,60*5);
        String content = "尊敬的邮箱用户："+email.getTos()+"归属者，您好！！！\n"
                + "\n本次请求的邮件验证码为:" + verCode + ",本验证码 5 分钟内效，请及时输入。（请勿泄露此验证码）\n"
                + "\n如非本人操作，请忽略该邮件。\n(这是一封通过自动发送的邮件，请不要直接回复）";
        email.setContent(content);
        email.setSubject("声语文创作-验证码服务");
        Boolean check = sendTextMail(email.getTos(), email.getSubject(), email.getContent());
        if(check) {
            //将key的值传递给前端，以方便验证使用
            return AjaxResult.success("发送成功" );
        } else {
            return AjaxResult.error(500, "发送失败");
        }
    }

    @Override
    public AjaxResult verityEmailCode(String emailCode, String tos) {
        //从redis中得到验证码
        String exist = (String)redisUtil.get(tos);
        if(StringUtils.isEmpty(exist)){//如果等于null，则表示5分钟已过，验证码失效
            return AjaxResult.error("验证码有效期已过！");
        }
        if(!StringUtils.isEmpty(exist) && !exist.equals(emailCode)){//验证码输入错误
            System.out.println();
            return AjaxResult.error("验证码输入错误，或者最新的验证码已经变更！");
        }
        return AjaxResult.success("验证成功");
    }
}
